from PyQt6.QtWidgets import (
    QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout,
    QListWidget, QListWidgetItem, QLineEdit, QMessageBox, QInputDialog
)
from utils.communication import send_request
from ui.dialogs import show_info, show_error

class AdminWindow(QWidget):
    def __init__(self, main_window=None):
        super().__init__()
        self.main_window = main_window  # 保存主窗口引用
        self.setWindowTitle("管理员界面 - 菜品与订单管理")
        self.resize(600, 500)

        # 菜品列表控件
        self.dish_list_widget = QListWidget()
        # 订单列表控件
        self.order_list_widget = QListWidget()

        # 菜品管理按钮
        self.btn_add_dish = QPushButton("添加菜品")
        self.btn_edit_dish = QPushButton("编辑选中菜品")
        self.btn_delete_dish = QPushButton("删除选中菜品")
        self.btn_refresh_dishes = QPushButton("刷新菜品列表")

        # 订单管理按钮
        self.btn_refresh_orders = QPushButton("刷新订单列表")
        self.btn_mark_done = QPushButton("标记订单为完成")

        # 菜品管理布局
        dish_btn_layout = QHBoxLayout()
        dish_btn_layout.addWidget(self.btn_add_dish)
        dish_btn_layout.addWidget(self.btn_edit_dish)
        dish_btn_layout.addWidget(self.btn_delete_dish)
        dish_btn_layout.addWidget(self.btn_refresh_dishes)

        # 订单管理布局
        order_btn_layout = QHBoxLayout()
        order_btn_layout.addWidget(self.btn_refresh_orders)
        order_btn_layout.addWidget(self.btn_mark_done)

        # 主布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(QLabel("菜品列表"))
        main_layout.addWidget(self.dish_list_widget)
        main_layout.addLayout(dish_btn_layout)

        main_layout.addWidget(QLabel("订单列表"))
        main_layout.addWidget(self.order_list_widget)
        main_layout.addLayout(order_btn_layout)
        # 返回主页面按钮
        self.btn_back = QPushButton("返回主页面")
        main_layout.addWidget(self.btn_back)

        self.setLayout(main_layout)

        # 绑定按钮事件
        self.btn_add_dish.clicked.connect(self.add_dish)
        self.btn_edit_dish.clicked.connect(self.edit_dish)
        self.btn_delete_dish.clicked.connect(self.delete_dish)
        self.btn_refresh_dishes.clicked.connect(self.load_dishes)
        self.btn_back.clicked.connect(self.back_to_main)

        self.btn_refresh_orders.clicked.connect(self.load_orders)
        self.btn_mark_done.clicked.connect(self.mark_order_done)
        # 初始加载数据
        self.load_dishes()
        self.load_orders()

    def load_dishes(self):
        request = {"action": "getDishes"}
        response = send_request(request)
        self.dish_list_widget.clear()
        if response is None:
            show_error(self, "错误", "服务器无响应，无法加载菜品")
            return
        dishes = response.get("dishes", [])
        for dish in dishes:
            item = QListWidgetItem(f"{dish['id']}: {dish['name']} ￥{dish['price']:.2f}")
            item.setData(1000, dish)
            self.dish_list_widget.addItem(item)

    def add_dish(self):
        name, ok1 = QInputDialog.getText(self, "添加菜品", "菜品名称:")
        if not ok1 or not name.strip():
            return
        price_str, ok2 = QInputDialog.getText(self, "添加菜品", "菜品价格（元）:")
        if not ok2 or not price_str.strip():
            return
        try:
            price = float(price_str)
        except ValueError:
            show_error(self, "错误", "价格格式不正确")
            return

        request = {
            "action": "addDish",
            "name": name.strip(),
            "price": price
        }
        response = send_request(request)
        if response is None:
            show_error(self, "错误", "服务器无响应，添加失败")
            return
        if response.get("result") is True:
            show_info(self, "成功", "菜品添加成功")
            self.load_dishes()
        else:
            show_error(self, "失败", "添加菜品失败")

    def edit_dish(self):
        item = self.dish_list_widget.currentItem()
        if item is None:
            show_error(self, "错误", "请选择要编辑的菜品")
            return
        dish = item.data(1000)
        name, ok1 = QInputDialog.getText(self, "编辑菜品", "菜品名称:", text=dish['name'])
        if not ok1 or not name.strip():
            return
        price_str, ok2 = QInputDialog.getText(self, "编辑菜品", "菜品价格（元）:", text=str(dish['price']))
        if not ok2 or not price_str.strip():
            return
        try:
            price = float(price_str)
        except ValueError:
            show_error(self, "错误", "价格格式不正确")
            return

        request = {
            "action": "editDish",
            "id": dish['id'],
            "name": name.strip(),
            "price": price
        }
        response = send_request(request)
        if response is None:
            show_error(self, "错误", "服务器无响应，编辑失败")
            return
        if response.get("result") is True:
            show_info(self, "成功", "菜品编辑成功")
            self.load_dishes()
        else:
            show_error(self, "失败", "编辑菜品失败")

    def delete_dish(self):
        item = self.dish_list_widget.currentItem()
        if item is None:
            show_error(self, "错误", "请选择要删除的菜品")
            return
        dish = item.data(1000)
        confirm = QMessageBox.question(self, "确认删除", f"确定要删除菜品 {dish['name']} 吗？")
        if confirm != QMessageBox.StandardButton.Yes:
            return

        request = {
            "action": "deleteDish",
            "id": dish['id']
        }
        response = send_request(request)
        if response is None:
            show_error(self, "错误", "服务器无响应，删除失败")
            return
        if response.get("result") is True:
            show_info(self, "成功", "菜品删除成功")
            self.load_dishes()
        else:
            show_error(self, "失败", "删除菜品失败")

    def load_orders(self):
        request = {"action": "getOrders"}
        response = send_request(request)
        self.order_list_widget.clear()
        if response is None:
            show_error(self, "错误", "服务器无响应，无法加载订单")
            return
        orders = response.get("orders", [])
        for order in orders:
            status = "已完成" if order.get("status") == "done" else "未完成"
            items = order.get("items", [])
            items_text = ", ".join(f"{item['dishName']} x{item['quantity']}" for item in items)
            item_text = f"订单ID: {order['id']} 用户: {order['username']} 状态: {status}\n  菜品: {items_text}"
            item = QListWidgetItem(item_text)
            item.setData(1000, order)
            self.order_list_widget.addItem(item)


    def mark_order_done(self):
        item = self.order_list_widget.currentItem()
        if item is None:
            show_error(self, "错误", "请选择要标记完成的订单")
            return
        order = item.data(1000)
        if order.get("status") == "done":
            show_info(self, "提示", "订单已经是完成状态")
            return

        request = {
            "action": "updateOrderStatus",
            "id": order['id']
        }
        response = send_request(request)
        if response is None:
            show_error(self, "错误", "服务器无响应，操作失败")
            return
        if response.get("result") is True:
            show_info(self, "成功", "订单已标记为完成")
            self.load_orders()
        else:
            show_error(self, "失败", "操作失败")
    def back_to_main(self):
        if self.main_window:
            self.main_window.show()  # 重新显示主界面
        self.close()  # 关闭当前窗口
